package com.faxsun.core.service.shop.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.faxsun.core.persist.entity.UserPO;

@Component
public class AccountOperation {

	private Logger LOG = LoggerFactory.getLogger(AccountOperation.class);

	@Value("${faxsun.api.shop.url}")
	private String apiPrefixUrl = "http://192.168.1.210:21111/faxsun/api/v1/";

	/*
	 * private String
	 * apiUrl="http://localhost:8080/faxsun/api/v1/customer/register"; private
	 * String apiLoginUrl="http://192.168.1.210:8081/api/v1/customer/login";
	 */
	/**
	 * 在电商注册用户，返回注册后的customer_id
	 * 
	 * @param email
	 * @param password
	 * @return
	 * @throws Exception
	 */
	public Long register(String email, String password) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		if (!this.apiPrefixUrl.endsWith("/")) {
			this.apiPrefixUrl += "/";
		}
		String apiUrl = this.apiPrefixUrl + "customer/register";
		HttpPost post = new HttpPost(apiUrl);

		try {
			List<NameValuePair> formParams = new ArrayList<NameValuePair>();
			formParams.add(new BasicNameValuePair("username", email));
			formParams.add(new BasicNameValuePair("password", password));
			UrlEncodedFormEntity uefEntity;
			uefEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
			post.setEntity(uefEntity);
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");
			CloseableHttpResponse response1 = httpclient.execute(post);
			String response = EntityUtils.toString(response1.getEntity());
			LOG.debug(response);
			ObjectMapper mapper = new ObjectMapper();
			JsonNode tree = mapper.readTree(response);
			String httpStatus = tree.get("httpStatusCode") == null ? null
					: tree.get("httpStatusCode").asText();
			if (httpStatus == null) {
				return (tree.get("id").asLong());
			} else if (httpStatus.equals("409")) {
				throw new RuntimeException("用户名（邮箱）已经存在，请直接登录或更换邮箱!");
			} else {
				return null;
			}

		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 调用商城的api验证用户名和密码。若返回值中，id存在，则验证通过
	 * 
	 * @param username
	 * @param password
	 * @return
	 * @throws Exception
	 */
	public UserPO login(String username, String password) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		if (!this.apiPrefixUrl.endsWith("/")) {
			this.apiPrefixUrl += "/";
		}
		String apiUrl = this.apiPrefixUrl + "customer/login";
		HttpPost post = new HttpPost(apiUrl);

		try {
			List<NameValuePair> formParams = new ArrayList<NameValuePair>();
			formParams.add(new BasicNameValuePair("username", username));
			formParams.add(new BasicNameValuePair("password", password));
			UrlEncodedFormEntity uefEntity;
			uefEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
			post.setEntity(uefEntity);
			// FIXME: use constant instead of string constant
			post.addHeader("Content-Type", "application/x-www-form-urlencoded");
			CloseableHttpResponse response1 = httpclient.execute(post);
			String response = EntityUtils.toString(response1.getEntity());
			LOG.debug(response);
			ObjectMapper mapper = new ObjectMapper();
			JsonNode tree = mapper.readTree(response);
			Long uid = (tree.get("id") == null ? null : tree.get("id").asLong());
			String usernameFromShop = (tree.get("username") == null ? null
					: tree.get("username").asText());
			String name = (tree.get("firstName") == null ? null : tree.get(
					"firstName").asText());
			String email = (tree.get("emailAddress") == null ? null : tree.get(
					"emailAddress").asText());
			String mobile = (tree.get("phone") == null ? null : tree.get(
					"phone").asText());

			UserPO userPO = new UserPO();
			// 将json字符串，转为本地存储信息，以便于user在资讯不存在的情况下，进行保存
			userPO.setUserId(uid);
			userPO.setUsername(usernameFromShop);
			userPO.setName(name);
			userPO.setEmail(email);
			userPO.setMobile(mobile);
			userPO.setRoleLevel(0);
			// 设置默认头像
			userPO.setAvatar("/src/img/avatar/head.png");
			return userPO;

			// id存在且返回值不为空，则登录成功
			/*
			 * if (uid != null && uid > 0L) { return Boolean.TRUE; } else {
			 * return Boolean.FALSE; }
			 */

		} catch (Exception e) {
			throw e;
		}
	}
}
